<?php

/**
 * CMGeneralCodeValue form.
 *
 * @package    form
 * @subpackage CMGeneralCodeValue
 * @version    SVN: $Id: sfPropelFormTemplate.php 6174 2007-11-27 06:22:40Z fabien $
 */
class PluginCMGeneralCodeValueForm extends BaseCMGeneralCodeValueForm
{
  public function setup()
  {
    parent::setup();
    
    //Status time is updated automatically.
    unset($this['status_time']);
    
    $this->widgetSchema['status_cd'] = new rhWidgetGenCodeSelect(
        array('code_set_nm'=>'Code_STS', 'add_empty'=>false));
    $this->widgetSchema['assigning_authority_cd'] = new rhWidgetGenCodeSelect(
        array('code_set_nm'=>'Code_AUTH', 'add_empty'=>false));
    
    $this->widgetSchema->setNameFormat('cm_general_code_value[%s]');
    
    //If this is a new form - then allow them to define the code. 
    if ($this->isNew())
      $this->widgetSchema['code'] = new sfWidgetFormInput();


    $this->validatorSchema['code_set_nm'] = new sfValidatorDoctrineChoice(
            array('model' => 'CMCodeSet', 
                  'column' => 'code_set_nm', 'required' => true));
    if ($this->isNew())
      $this->validatorSchema['code'] = new sfValidatorString(
          array('min_length' => 1, 'max_length'=> 36), 
          array('invalid'=> 'Code set name must be between 1 and 36 characters.'));
    
/*
 * TODO: Make validator which allows effective_to_time to be blank even when from time is set.
 */ 
    if ($this->isNew())
    {
      $this->validatorSchema->setPostValidator(new sfValidatorAnd(array(
      new sfValidatorCallback(
        array(
          'callback' => array($this, 'duplicateCheck'),
          'arguments' => array(),
        ),
        array('invalid'  => 'Code is already being used in this code set.')
      ),
      new sfValidatorSchemaCompare('effective_from_time', sfValidatorSchemaCompare::LESS_THAN_EQUAL, 'effective_to_time',
          array('throw_global_error' => false),
          array('invalid' => 'The effective from time ("%left_field%") must be before effective to time ("%right_field%")')
      ),
      )));
    }
    else
    {
      $this->validatorSchema->setPostValidator(
        new sfValidatorSchemaCompare('effective_from_time', sfValidatorSchemaCompare::LESS_THAN_EQUAL, 'effective_to_time',
          array('throw_global_error' => false),
          array('invalid' => 'The effective from time ("%left_field%") must be before effective to time ("%right_field%")')
      ));
    }
    
    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

  }
  public function duplicateCheck($validator, $value) 
  {
    $query = false;
    $query = CMGeneralCodeValue::getCodeValue($value['code_set_nm'], $value['code']);
   
    if($query)
    {
      throw new sfValidatorError($validator, 'invalid'); // Code_set_nm already exists
    } 
    else 
    {
      return $value; // Code_set_nm does not exist
    }
  }

  public function getModelName()
  {
    return 'CMGeneralCodeValue';
  }
}
